package com.qlm.service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.qlm.cache.CacheManmager;
import com.qlm.cache.ShopCache;
import com.qlm.entity.Address;
import com.qlm.entity.Comment;
import com.qlm.entity.Order;
import com.qlm.entity.ResultMsg;
import com.qlm.entity.ShopCar;
import com.qlm.entity.User;
import com.qlm.entity.Yhq;
import com.qlm.tool.WxUtil;

public class ShopMgr {
	
	static Logger logger = LoggerFactory.getLogger(ShopMgr.class);

	static ShopCache shopCache = CacheManmager.getObj("shop");
	public static List<Record> getComments(String id){
		return Db.find("select * from t_comment where gift_id_ = "+id+" and isgood = 1 order by time_ desc");
	}
	
	public static List<Record> getShopCar(String openid){
		return Db.find("select * from t_car where openid_ = '"+openid+"'");
	}
	
	public static void delShopCar(String id){
		Db.update("delete from t_car where id ="+id);
	}
	
	public static void updateShopCarNum(String id,String count){
		Db.update("update  t_car set count_ = "+count+" where id = "+id );
	}
	
	public static List<Record> getOrderByUser(String openid){
		List<Record> find = Db.find("select * from t_order where openid_ = '"+openid+"' order by create_time_ desc");
		return find;
	}
	
	/**
	 * 获取订单
	 * @param id
	 * @return
	 */
	public static Record getOrder(String id,String openid){
		Record findFirst = Db.findFirst("select * from t_order where id = ?",id);
		Integer addressid = WxUtil.getInt("addr_id_", findFirst);
		Record address = getAddress(addressid);
		findFirst.set("address", address);
		List<Record> find = Db.find("select * from t_order_detail where order_id_ = ?",id);
		for (Record record : find) {
			Integer giftId = WxUtil.getInt("gift_id_", record);
			Record gift = shopCache.getGift(giftId+"",openid);
			Object name_ = gift.get("name_");
			Object img_ = gift.get("img_");
			record.set("name_", name_);
			record.set("img_", img_);
		}
		findFirst.set("gifts", find);
		return findFirst;
	}
	
	public static List<Record> getYhq(double money,String openid){
		List<Record> find = Db.find("select * from t_yhq where openid_ = '"+openid+"' and dead_time_ >=now() and status_ = 0 and tmoney_ <= "+money);
		return find;
	}
	
	/**
	 * 获取地址
	 * @param user
	 * @return
	 */
	public static Record [] getAddress(User user){
		Integer default_id = WxUtil.getInt("def_add", user,-1);
		String openid = user.getStr(UserService.OPENID);
		List<Record> find = Db.find("select * from t_addr where openid_ ='"+openid+"' and status_ <>1 order by id desc");
		Record [] res = new Record[find.size()];
		int i = 1;
		for (Record record : find) {
			Integer id = WxUtil.getInt("id", record);
			if(default_id == id){
				res[0] = record;
			}else{
				res[i] = record;
				i++;
			}
		}
		return res;
	}
	
	public static void deleteAddress(String id,String openid){
		Db.update("update  t_addr set status_ = 1 where id = ?",id);
		logger.info("用户"+openid+"删除收货地址"+id);
	}
	
	/**
	 *获取收获地址
	 */
	public static Record getAddress(int id){
		Record find = Db.findFirst("select * from t_addr where id ="+id);
		return find;
	}
	
	public static ResultMsg saveAddress(String id,User user,String name,String tel,String address,boolean setDef){
		Integer default_id = WxUtil.getInt("def_add", user,-1);
		ResultMsg msg = new ResultMsg();
		String openid = user.getStr(UserService.OPENID);
		Address add = null;
		if("".equals(id)){//新增
			add = new Address();
			add.set("name_", name).set("status_", 0).set("mobile_", tel).set("addr_", address).set("openid_", openid).save();
		}else{
			add = Address.dao.findById(id);
			add.set("name_", name).set("mobile_", tel).set("addr_", address).update();
		}
		if(default_id == -1){
			setDef = true;
		}
		if(setDef){
			Integer defId = WxUtil.getInt("id", add);
			user.set("def_add", defId).update();
		}
		return msg;
	}
	
	public static void getYhq(User user , double total){
		
	}
	
	public static ResultMsg addComment(String id, String text, User user,String oid,String orderid) {
		ResultMsg rm = new ResultMsg();
		Comment c = new Comment();
		String nick_name = user.getStr(UserService.NICK_NAME);
		String img_ = user.getStr(UserService.HEAD_PIC);
		Db.update("update t_order_detail set iscomment = 1 where id = "+oid);
		checkFinishOrder(orderid);
		c.set("img_", img_).set("nick_name_", nick_name).set("content_", text).set("gift_id_", id).set("time_", new Date()).save();
		rm.setStatus(true);
		return rm;
	}
	
	/**
	 * 评论完后检查订单是否完成
	 * @param orderid
	 */
	private static void checkFinishOrder(String orderid) {
		List<Record> find = Db.find("select * from t_order_detail where order_id_ = '"+orderid+"'");
		for (Record record : find) {
			Integer iscomment = WxUtil.getInt("iscomment",record);
			if(iscomment != 1){
				return;
			}
		}
		Db.update("update t_order set status_ = 3 where id = '"+orderid+"'");
		logger.info("完成订单");
	}

	public static void cancelOrder(String id){
	}
	
	public static ResultMsg receive(String id,String openid){
		ResultMsg rm = new ResultMsg();
		Db.update("update t_order set status_ = 2 where id = ?",id);
		rm.setStatus(true);
		logger.info("用户:"+openid+",确认收货,订单："+id);
		return rm;
	}
	
	public static ResultMsg addOrder(User user, String vals, String address, String beizhu, String yhqval) {
		ResultMsg msg = new ResultMsg();
		Order o = new Order();
		String openid = user.getStr(UserService.OPENID);
		JSONArray arrs = JSONArray.parseArray(vals);
		int size = arrs.size();
		double total = 0;
		StringBuilder sb = new StringBuilder();
		String no = getOrderNo();
		List<String> sqls = new ArrayList<String>();
		for (int i = 0; i < size; i++) {
			JSONObject obj = arrs.getJSONObject(i);
			String giftid = obj.getString("id");
			Record gift = shopCache.getGift(giftid,openid);
			String count = obj.getString("count");
			String shopcarid = obj.getString("shopcarid");
			String price_ = WxUtil.getStr("price_", gift);
			total += getPrice(price_, count);
			if (sb.length() > 0) {
				sb.append(",");
			}
			sqls.add("insert into t_order_detail values(NUll,"+giftid+","+count+",'"+price_+"','"+no+"',0)");
			sb.append(shopcarid);
		}
		Db.update("delete from t_car where id in ("+sb.toString()+")");//删除购物车
		Db.batch(sqls, 300);
		double yhqPrice = getYHQPrice(total, yhqval);
		String yhprice = (total - yhqPrice)+"";
		BigDecimal yhprice_ = new BigDecimal(yhprice);
		yhprice = yhprice_.setScale(2,   BigDecimal.ROUND_HALF_UP).doubleValue()+"";
		o.set("price_", yhqPrice + "").set("create_time_", new Date()).set("id", no).set("status_", 0).set("openid_",openid)
				.set("addr_id_", address).set("remark_", beizhu).set("yhq_", yhprice).set("yhqid_", yhqval).save();
		logger.info("用户"+openid+"创建订单："+o);
		msg.setStatus(true);
		msg.setObj(o);
		return msg;
	}
	
	private static double getPrice(String price_,String count){
		BigDecimal multiply = new BigDecimal(price_).multiply(new BigDecimal(count));
		return multiply.doubleValue();
	}
	
	private static String getOrderNo(){
		String order = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
		Random r = new Random();
		for (int i = 0; i < 6; i++) {
			order += r.nextInt(9);
		}
		return order;
	}
	
	private static double getYHQPrice(double total ,String yhqid){
		if("-1".equals(yhqid)) return total;
		Record re = Db.findFirst("select * from t_yhq where id = ?",yhqid);
		Integer type = WxUtil.getInt("type_", re);
		if(type == 1){//减的
			double yhmoney_ = re.getDouble("yhmoney_");
			BigDecimal subtract = new BigDecimal(total).subtract(new BigDecimal(yhmoney_));
			total   =  subtract.setScale(2,   BigDecimal.ROUND_HALF_UP).doubleValue(); 
		}else if(type == 2){
			String discount_ = re.getStr("discount_");
			BigDecimal subtract = new BigDecimal(discount_).multiply(new BigDecimal(total));
			total   =  subtract.setScale(2,   BigDecimal.ROUND_HALF_UP).doubleValue(); 
		}
		Db.update("update t_yhq set status_ = 1 where id = "+yhqid);
		logger.info("使用优惠券"+yhqid);
		return total;
	}
	
	public static ResultMsg addShopCar(String openid,String id,String count){
		ResultMsg msg = new ResultMsg();
		ShopCar car = ShopCar.dao.findFirst("select * from t_car where openid_ = '"+openid+"' and gift_id_ = "+id);
		if(car == null){
			car = new ShopCar();
			car.set("openid_", openid).set("gift_id_", id).set("count_", count).save();
			msg.setStatus(true);
			msg.setMsg("已经添加到购物车啦");
		}else{
			car.set("count_", count).update();
			msg.setStatus(false);
			msg.setMsg("已经添加到购物车啦");
		}
		return msg;
	}
	
	public static List<Record> getYHQ(String openid){
		List<Record> find = Db.find("select * from t_yhq where openid_ = '"+openid+"'");
		return find;
	}
	
	public static void addShare(String curopenid,String shareid){
		if(curopenid.equals(shareid)){
			return;
		}
		if(shareid == null || "".equals(shareid)){
			return;
		}
		Db.update("insert into t_share (openid_,shareid_,time_) values('"+shareid+"','"+curopenid+"',now())");
		logger.info("分享添加的用户,当前用户:"+curopenid+",推荐人:"+shareid);
	}
	
	/**
	 * 
	 * @param openid
	 * @param type
	 * 1为 满50 减10
	 * 2为 满100 减30
	 */
	public static void sendYhq(String openid,int type){
		int yhmoney = 10,tmoney = 50;
		String desc = "满50元减10元";
		if(type == 2){
			yhmoney = 30;tmoney = 100;
			desc = "满100元减30元";
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date parse = new Date();
		try {
			parse = sdf.parse("2017-11-26");
		} catch (ParseException e) {
			e.printStackTrace();
		}
		Yhq yhq = new Yhq();
		yhq.set("yhmoney_", yhmoney).set("tmoney_", tmoney).set("dead_time_", parse).set("openid_", openid).set("status_", 0)
		.set("desc_", desc).set("create_time_", new Date()).set("type_", 1).save();
		logger.info("添加优惠券openid:"+openid+",描述:"+desc);
	}

	/**
	 *  修改收货地址
	 * @param orderid
	 * @param addrId
	 */
	public static ResultMsg modifyAddrees(String orderid, int addrId) {
		ResultMsg msg = new ResultMsg();
		Order.dao.findById(orderid).set("addr_id_", addrId).update();
		logger.info("更新订单收货地址,"+orderid+",收货:"+addrId);
		msg.setStatus(true);
		return msg;
		
	}

	public static ResultMsg cancerOrder(String id) {
		ResultMsg msg = new ResultMsg();
		Order order = Order.dao.findById(id);
		order.set("status_", -1).update();
		Integer yhqid = WxUtil.getInt("yhqid_", order,-1);
		if(yhqid != -1){
			Yhq findById = Yhq.dao.findById(yhqid);
			if(findById != null){
				findById.set("status_", 0).update();
				logger.info("退还用户优惠券：orderid:"+id);
			}
		}
		logger.info("用户取消订单:"+id);
		msg.setStatus(true);
		return msg;
	}
}
